//  
//  AppDelegate.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/4.
//  Copyright © 2015年  NorthCity. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        setUpAppearance()
        
        print(UserAccountViewModel.sharedUserAccount.userAccount)
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultRootViewController
        window?.makeKeyAndVisible()
        //    监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(TcgSwitchRootViewControllerNotification,
            object: nil,//发送通知的对象
            queue: nil)// nil 默认主线程
            { [weak self] (notifation) -> Void in
                let vc = notifation.object != nil ? WecomeViewController():MainViewController()
//                切换根控制器
                self?.window?.rootViewController = vc
        }
        return true
    }
    func applicationDidEnterBackground(application: UIApplication) {
        StatusDAL.clearDataCache()
    }
//    注销通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self,//监听者
            name: TcgSwitchRootViewControllerNotification,//通知
            object: nil)//发送通知对象
    }
//    设置全局背景颜色
    private func setUpAppearance(){
        UITabBar.appearance().tintColor = TcgAppearanceTintColor
        UINavigationBar.appearance().tintColor = TcgAppearanceTintColor
    }
}
//MARK:  - 界面切换
extension AppDelegate{
/// 默认根控制器
    private var defaultRootViewController:UIViewController{
        if UserAccountViewModel.sharedUserAccount.userLogin {
            return isNewVersion ? NewFeatureViewController():WecomeViewController()
        }
        return MainViewController()
    }
    
/// 判断是否是新版本
    private var isNewVersion:Bool{
//        1 当前版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
//        2 获取沙盒版本
        let sanBoxVersionKey = "sanBoxVersionKey"
        let sanBoxVersion  = NSUserDefaults.standardUserDefaults().doubleForKey(sanBoxVersionKey)
//        3 存储当前版本
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sanBoxVersionKey)
//        4 返回结果
        print(currentVersion)
        print(sanBoxVersion)
        return currentVersion > sanBoxVersion
    }
}


